import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
import schedule
import time
from datetime import datetime


from fun2 import read_plc

# 邮箱配置
email_config = {
    'smtp_server': 'smtp.qq.com',
    'smtp_port': 465,
    'sender_email': '@qq.com',
    'sender_password': '',
    'receiver_email': '@qq.com'
}


# Excel 文件路径
excel_file_path = 'output_data.xlsx'

def fetch_data_and_save_to_excel():
    try:
        # 从PLC获取数据
        value1, value2 = read_plc()
        # 获取今天的日期
        today = datetime.today().date()
        data = {
            '日期': [today],
            '合格数': [value1],
            '不合格数': [value2]
        }
        df = pd.DataFrame(data)

        # 保存到Excel文件中
        df.to_excel(excel_file_path, index=False)
        print(f"Data saved to {excel_file_path}")

        # 发送邮件
        send_email_with_attachment()
    except Exception as e:
        print("Error:", str(e))

def send_email_with_attachment():
    msg = MIMEMultipart()
    msg['From'] = email_config['sender_email']
    msg['To'] = email_config['receiver_email']
    msg['Subject'] = '数据报表 - Excel附件'

    body = '这是您的数据库报表，请查收附件。'
    msg.attach(MIMEText(body, 'plain'))

    # 添加附件
    try:
        with open(excel_file_path, 'rb') as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                f'attachment; filename="{os.path.basename(excel_file_path)}"'
            )
            msg.attach(part)

        # 使用 SMTP_SSL 发送邮件（QQ邮箱465端口需要SSL）
        server = smtplib.SMTP_SSL(email_config['smtp_server'], email_config['smtp_port'])
        server.login(email_config['sender_email'], email_config['sender_password'])
        server.sendmail(email_config['sender_email'], email_config['receiver_email'], msg.as_string())
        print("Email sent successfully")
    except Exception as e:
        print("Failed to send email:", str(e))
    finally:
        try:
            server.quit()
        except:
            pass  # 如果server未定义，忽略关闭操作


if __name__ == '__main__':
    # 先执行一次
    try:
        fetch_data_and_save_to_excel()
    except Exception as e:
        print("Initial run failed:", e)
        exit(1)

    # 定时任务设置（每天早上8点执行）
    schedule.every().day.at("08:00").do(fetch_data_and_save_to_excel)

    print("Starting scheduler...")
    while True:
        schedule.run_pending()
        time.sleep(60)